<?php
/*
Extension Name: ModTools
Extension Url: http://lussumo.com/addons
Description: Allows users to mod comments and discussions.
Version: 0.06.10b 
Author: jawele
Author Url: http://jawele.com
*/

/*
USE IT AT YOUR OWN RISK!
I'M NOT RESPONSABLE BY ANY MEANS ON ANY DAMMAGE THAT THIS EXTENSION COULD DO.
YOU'VE BEEN WARNED!
*/

// TODO display in the discussion grid the discussion ID and also in the comment grid maybe as heading
//
//
if (!defined('IN_VANILLA')) exit();
if(!isset($Head)) return;
$Context->Dictionary['MergeModeTab'] = 'Merge Mode';
$Context->Dictionary['StartModDisc'] = 'Start Mod Disc';
$Context->Dictionary['DiscussionAsMod'] = 'Discussion As Mod';
$Context->Dictionary['ModToolsStartNew'] = 'Mod Tools Start New...';
$Context->Dictionary['SwitchToMergeMode'] = 'Switch To Merge Mode';
$Context->Dictionary['SwitchToSplitMode'] = 'Switch To Split Mode';
$Context->Dictionary['HideMergeMode'] = 'Hide Merge Mode';
$Context->Dictionary['HideSplitMode'] = 'Hide Split Mode';
$Context->Dictionary['MoveDiscussionTo'] = 'Move Discussion To:';
$Context->Dictionary['MoveNow'] = 'Move Now!';
$Context->Dictionary['ModToolsOptions'] = 'ModTools Options';
$Context->Dictionary['Select'] = 'Select';
$Context->Dictionary['CheckAllForTotalMerge'] = 'Check All For Total Merge';
$Context->Dictionary['UnCheckAll'] = 'UnCheck All';
$Context->Dictionary['SplitModeTab'] = 'Split Mode';
$Context->Dictionary['ModModeTab'] = 'Mod Tools';
$Context->Dictionary['ErrorModeTab'] = 'Mod Error';
$Context->Dictionary['SelectDiscussionToSplit'] = 'SPLIT';
$Context->Dictionary['SelectDiscussionToMerge'] = 'MERGE';
$Context->Dictionary['SelectDiscussionToModerate'] = 'MODERATE';
$Context->Dictionary['Split'] = 'Split';
$Context->Dictionary['Merge'] = 'Merge';
$Context->Dictionary['DiscussionIDnumber'] = 'Discussion ID';
$Context->Dictionary['DiscussionIDWhereToMerge'] = 'DiscussionID Where To Merge';
$Context->Dictionary['MergeThisDiscussion'] = 'Merge This Discussion';
$Context->Dictionary['SplitThisDiscussion'] = 'Split This Discussion';
$Context->Dictionary['QuickModDiscussionID'] = 'Quick Mod DiscussionID';
$Context->Dictionary['InputNewDiscussionTitle'] = 'Input New Discussion Title';
$Context->Dictionary['SetNewTitleNow'] = 'Set New Title Now!';
$Context->Dictionary['GoToModTools'] = 'Go To Mod Tools';
$Context->Dictionary['ModerateThisDiscussion'] = 'Moderate this Discussion';
$Context->Dictionary['ForgetNameField'] = 'Hey! what kind of moderator you are? you forgot the discussion name field!';
$Context->Dictionary['ForgetNewDiscField'] = 'You forgot the new discussion ID!';
$Context->Dictionary['ForgetBody'] = 'You forgot the body!';
$Context->Dictionary['ForgetCheckComment'] = 'You forgot to check comments!';
$Context->Dictionary['ForgetBoth'] = 'You forgot to check comments and to enter the name input in the field';
$Context->Dictionary['ForgetBothNameBody'] = 'You forgot to enter the name and body';
$Context->Dictionary['DiscussionIDtoMerge'] = 'DiscussionID Where To Merge';
$Context->Dictionary['WrongDiscussionID'] = 'The discussion id doesn\'t exist check your discussion id input';
$Context->Dictionary['MessDiscussionID'] = 'The normal usage of merge is to use it on newly created discussion and where the destination Discussion ID is an old discussion otherways it doesn\'t make sense and it\'s a mess ';
$Context->Dictionary['PERMISSION_MODERATE_COMMENTS'] = 'Can moderate any comment and discussion';
$Context->Dictionary['Moderate'] = 'Moderate';

//rewrite configs
$Context->Configuration['REWRITE_extension.php?PostBackAction=Split'] = 'extension.php?PostBackAction=Split';
$Context->Configuration['REWRITE_extension.php?PostBackAction=Merge'] = 'extension.php?PostBackAction=Merge';
$Context->Configuration['REWRITE_extension.php?PostBackAction=StartDiscAsMod'] = 'extension.php?PostBackAction=StartDiscAsMod';


AddConfigurationSetting($Context, 'TAB_POSITION_MOD_TOOLS', '110');

$Head->AddScript('extensions/ModTools/function.js');
$Head->AddStyleSheet('extensions/ModTools/style.css');

$Configuration['PERMISSION_MODERATE_COMMENTS'] = '0';


if ( $Context->Session->User->Permission('PERMISSION_MODERATE_COMMENTS') && !(in_array($Context->SelfUrl, array("people.php"))) ) {
	$ModTitle = $Context->GetDefinition('ModToolsStartNew');
	$Panel->AddList($ModTitle, 11,1);
	$Panel->AddListItem($ModTitle, $Context->GetDefinition('DiscussionAsMod'), './extension.php?PostBackAction=ShowStartDiscAsMod&DiscussionID=0"','','');

if (in_array($Context->SelfUrl, array("comments.php")) )
	{
		$DiscID = ForceIncomingString('DiscussionID','0');
		$ModToolsPanelLink = $Context->GetDefinition('QuickModDiscussionID').' '.$DiscID;
		$ModToolsMoreOptions = $Context->GetDefinition('GoToModTools');
		$Panel->AddList($ModToolsPanelLink, 11,2);
		$Panel->AddList($ModToolsMoreOptions,11,3);
		if ( ForceIncomingString("PostBackAction", "") != ('ShowModTools' && 'ShowModSplit' && 'ShowModMerge' && 'ShowStartDiscAsMod') )
		{
			$Panel->AddListItem($ModToolsMoreOptions, $Context->GetDefinition('ModerateThisDiscussion'), './extension.php?PostBackAction=ShowModTools&DiscussionID='.$DiscID.'"','','');
		}
		$Panel->AddListItem($ModToolsPanelLink, $Context->GetDefinition('InputNewDiscussionTitle'), '#','','onclick="urlDiscID(\''.$DiscID.'\'); setTitle(\''.$GLOBALS['Context']->Configuration['WEB_ROOT'].'\',\''.$DiscID.'\'); "');
		$Panel->AddListItem($ModToolsPanelLink, $Context->GetDefinition('SetNewTitleNow'), '#','','id="subjectTitle"');
	}

	$Context->AddToDelegate('DiscussionGrid', 'PostDiscussionOptionsRender', 'DiscussionOptions_AddSelectModTools');
	function DiscussionOptions_AddSelectModTools (&$Form)
	{
		if ( $Form->Context->Session->User->Permission('PERMISSION_MODERATE_COMMENTS') )
		{
			$C = $Form->DelegateParameters['Discussion'];
			// check if tabled theme is on, so then it will not screw up the discussions page
			if (!(preg_match('/tabled/i', $Form->Context->Configuration['DEFAULT_STYLE']))){
				$Form->DelegateParameters['DiscussionList'] .= 
				'<li class="DiscussionLastComment"><span><a href="./extension.php?PostBackAction=ShowModTools&DiscussionID='.$C->DiscussionID.'" id="ModDiscussion'.$C->DiscussionID.'">'.$Form->Context->GetDefinition('SelectDiscussionToModerate').'</a></span></li>
				<li class="DiscussionLastComment"><span>
				'.$Form->Context->GetDefinition('DiscussionIDnumber').'</span></li>&nbsp;'.$C->DiscussionID.'';
			}
		}
	}

}

class ModerationManager {
	var $Name;
	var $Context;
	var $FirstCommentID;
	var $NewDiscussion;
	var $ComIDs;
	var $CountComments;
	// Constructor
	function ModerationManager(&$Context) {
		$this->Name = 'ModerationManager';
		$this->Context = &$Context;
		$this->FirstCommentID= 0;
		$this->NewDiscussion = 1;
	}
	
	function UpdateWhispersTables ($WhisperUserID, $AuthorUserID, $currentDiscussionID, $NewDiscID, $DateWhisper)
	{	
		//we need to update the whisper discussion id to the newly created discussion
		$s = $this->Context->ObjectFactory->NewContextObject($this->Context, 'SqlBuilder');
		$s->Clear();
		$s->SetMainTable('DiscussionUserWhisperFrom', 'w');
		$s->AddFieldNameValue('DiscussionID' , $NewDiscID);
		$s->AddWhere('w', 'DiscussionID', '', $currentDiscussionID, '=');
		$s->AddWhere('w', 'WhisperFromUserID', '', $AuthorUserID, '='); 
		$this->Context->Database->Update($s, $this->Name, 'UpdateWhispersTables', 'An error occurred while updating discussion properties.');
		
		$s->Clear();
		$s->SetMainTable('DiscussionUserWhisperTo', 'w');
		$s->AddFieldNameValue('DiscussionID', $NewDiscID);
		$s->AddWhere('w', 'WhisperToUserID', '', $WhisperUserID, '=');
		$this->Context->Database->Update($s, $this->Name, 'UpdateWhispersTables', 'An error occurred while updating discussion properties.');
		
		//update counter whisper in current Discussion
			$s->Clear();
			$s->SetMainTable('Discussion', 'd');
			$s->AddFieldNameValue('TotalWhisperCount', $this->Context->DatabaseColumns['Discussion']['TotalWhisperCount'].'-1', '0');
			$s->AddWhere('d', 'DiscussionID', '', $currentDiscussionID, '=');
			$this->Context->Database->Update($s, $this->Name, 'UpdateWhispersTables', 'An error occurred while updating discussion properties.');

		//update counter whisper in new Discussion
		
		$s->Clear();
		$s->SetMainTable('Discussion', 'd');
		$s->AddFieldNameValue('TotalWhisperCount', $this->Context->DatabaseColumns['Discussion']['TotalWhisperCount'].'+1', '0');
		$s->AddWhere('d', 'DiscussionID', '', $NewDiscID, '=');
		$this->Context->Database->Update($s, $this->Name, 'UpdateWhispersTables', 'An error occurred while updating discussion properties.');
		
		// // and now update the from and to whisper columns in new Discussion
		// 
		// $s->Clear();
		// $s->SetMainTable('Discussion', 'd');
		// $s->AddFieldNameValue('WhisperToLastUserID', $WhisperUserID);
		// $s->AddFieldNameValue('WhisperFromLastUserID', $AuthorUserID);
		// $s->AddFieldNameValue('DateLastWhisper', $DateWhisper);
		// $s->AddWhere('d', 'DiscussionID', '', $NewDiscID, '=');
		// $this->Context->Database->Update($s, $this->Name, 'UpdateWhispersTables', 'An error occurred while updating discussion properties.');
	}
	
	function updateFromToWhisperInDiscussion ($DiscussionID)
	{
		$s = $this->Context->ObjectFactory->NewContextObject($this->Context, 'SqlBuilder');
		
		// we get the total counts of comments and whispers
		$s->Clear();
		$s->SetMainTable('Comment', 'c');
		$s->AddSelect(array('CommentID', 'WhisperUserID', 'DateCreated', 'AuthUserID'),'c');
		$s->AddWhere('c', 'DiscussionID', '', $DiscussionID, '=');
		$Result = $this->Context->Database->Select($s, $this->Name, 'updateFromToWhisperInDiscussion', 'An error occurred while selecting comment properties.');
		// we iterate thru all comments of current discussion
		while ($Row = $this->Context->Database->GetRow($Result)) {
			$CountComments = $Row['CommentID'];
			$WhisperUserID = $Row['WhisperUserID'];
			$DateWhisper = $Row['DateCreated'];
			$AuthorUserID = $Row['AuthUserID'];

			// if is a whisper we update the from, to and date last whisper columns in currentDisc
			
			if ( $WhisperUserID != 0)
			{
				$s->Clear();
				$s->SetMainTable('Discussion', 'd');
				$s->AddFieldNameValue('DateLastWhisper', $DateWhisper); // FIXME la data mi da null
				$s->AddFieldNameValue('WhisperToLastUserID', $WhisperUserID);
				$s->AddFieldNameValue('WhisperFromLastUserID', $AuthorUserID);
				$s->AddWhere('d', 'DiscussionID', '', $DiscussionID, '=');
				$this->Context->Database->Update($s, $this->Name, 'updateFromToWhisperInDiscussion', 'An error occurred while updating discussion properties.');
			}
		}
	}
	
	function StartNewDiscAsMod($TopicName,$Body,$CatID,$Sticky,$Close) {
		
		// Validate the Discussion topic
		$Name = FormatStringForDatabaseInput($TopicName);
		$Body = FormatStringForDatabaseInput($Body);
		Validate('Name', 1, $Name, 100, '', $this->Context);
		if ($CatID <= 0) $this->Context->WarningCollector->Add($this->Context->GetDefinition('ErrSelectCategory'));
	
		$UserManager = $this->Context->ObjectFactory->NewContextObject($this->Context, 'UserManager');
		$UserManager->UpdateUserDiscussionCount($this->Context->Session->UserID);
		
		// Validate first comment
		$Discussion->Comment->DiscussionID = $Discussion->DiscussionID;
		$Discussion->Comment->CommentID = 0;
		$CommentManager = $this->Context->ObjectFactory->NewContextObject($this->Context, 'CommentManager');
		$CommentManager->ValidateComment($Discussion->Comment, 0);
	
		// write the new discussion to db
		
		$s = $this->Context->ObjectFactory->NewContextObject($this->Context, 'SqlBuilder');
		$s->SetMainTable('Discussion', 'd');
		$s->AddFieldNameValue('Name', $Name);
		$s->AddFieldNameValue('CategoryID', $CatID);
		$s->AddFieldNameValue('Sticky', $Sticky);
		$s->AddFieldNameValue('Closed', $Close);
		$s->AddFieldNameValue('AuthUserID', $this->Context->Session->UserID);
		$s->AddFieldNameValue('CountComments', 0);
		$s->AddFieldNameValue('DateCreated', MysqlDateTime());
		$s->AddFieldNameValue('DateLastActive', MysqlDateTime());
		$Discussion->DiscussionID = $this->Context->Database->Insert($s, $this->Name, 'StartNewDiscAsMod', 'An error occurred while creating a new discussion.');
		$Discussion->Comment->DiscussionID = $Discussion->DiscussionID;
		$NewDisc = $Discussion->Comment->DiscussionID;
		
		$s->Clear();
		$s->SetMainTable('Comment', 'm');
		$s->AddFieldNameValue('Body', $Body);
		$s->AddFieldNameValue('FormatType', $Comment->FormatType);
		$s->AddFieldNameValue('RemoteIp', GetRemoteIp(1));
		$s->AddFieldNameValue('DiscussionID', $NewDisc);
		$s->AddFieldNameValue('AuthUserID', $this->Context->Session->UserID);
		$s->AddFieldNameValue('DateCreated', MysqlDateTime());
		$s->AddFieldNameValue('WhisperUserID', $Comment->WhisperUserID);
		
		$Comment->CommentID = $this->Context->Database->Insert($s, $this->Name, 'StartNewDiscAsMod', 'An error occurred while creating a new discussion comment.');

		// First update the counts & last user
		$s->Clear();
		$s->SetMainTable('Discussion', 't');
		$s->AddFieldNameValue('CountComments', $this->Context->DatabaseColumns['Discussion']['CountComments'].'+1', '0');
		$s->AddFieldNameValue('LastUserID', $this->Context->Session->UserID);
		$s->AddWhere('t', 'DiscussionID', '', $NewDisc, '=');
		$this->Context->Database->Update($s, $this->Name, 'StartNewDiscAsMod', "An error occurred while updating the discussion's comment summary.");
		
		// Now only update the DateLastActive if the discussion isn't set to Sink
		$s->Clear();
		$s->SetMainTable('Discussion', 't');
		$s->AddFieldNameValue('DateLastActive', MysqlDateTime());
		$s->AddWhere('t', 'DiscussionID', '', $NewDisc, '=');
		$s->AddWhere('t', 'Sink', '', '1', '<>', 'and');
		$this->Context->Database->Update($s, $this->Name, 'StartNewDiscAsMod', "An error occurred while updating the discussion's last active date.");
		
		$s->Clear();
		$s->SetMainTable('Discussion', 'd');
		$s->AddFieldNameValue('FirstCommentID', $Comment->CommentID);
		$s->AddWhere('d', 'DiscussionID', '', $NewDisc, '=');
		$this->Context->Database->Update($s, $this->Name, 'StartNewDiscAsMod', 'An error occurred while updating discussion properties.');
		
		if ($Discussion->Comment->DiscussionID) {
			// Saved successfully, so send back to the discussion
			header('location:'.GetUrl($this->Context->Configuration, 'comments.php', '', 'DiscussionID', $Discussion->Comment->DiscussionID, '', '', ''));
			die();
		}
		return $this->Context->WarningCollector->Iif();
		
	}
	
	function SplitDiscussion($TopicName,$CatID,$ComIDs,$currentDiscussionID) {
		
		// Validate the Discussion topic
		$Name = FormatStringForDatabaseInput($TopicName);
		Validate($this->Context->GetDefinition('DiscussionTopicLower'), 1, $Name, 100, '', $this->Context);
		if ($CatID <= 0) $this->Context->WarningCollector->Add($this->Context->GetDefinition('ErrSelectCategory'));
		
		// write the new discussion to db
		
		$s = $this->Context->ObjectFactory->NewContextObject($this->Context, 'SqlBuilder');
		$s->SetMainTable('Discussion', 'd');
		$s->AddFieldNameValue('Name', $TopicName);
		$s->AddFieldNameValue('CategoryID', $CatID);
		$s->AddFieldNameValue('DateCreated', MysqlDateTime());
		$s->AddFieldNameValue('DateLastActive', MysqlDateTime());
		$Discussion->DiscussionID = $this->Context->Database->Insert($s, $this->Name, 'SplitDiscussion', 'An error occurred while creating a new discussion.');
		$Discussion->Comment->DiscussionID = $Discussion->DiscussionID;
		$NewDisc = $Discussion->Comment->DiscussionID;
		
			//here we check the comments and split them
			// we make sure that array is sorted ok!!

		for ($j = 0; $j < sizeof($ComIDs); $j++) {
			$counter = (sizeof($ComIDs));
			$item = $ComIDs[$j];
			
			// we get info on the whispers before
			
			$s->Clear();
			$s->SetMainTable('Comment', 'c');
			$s->AddSelect(array('AuthUserID','WhisperUserID','DateCreated'),'c');
			$s->AddWhere('c', 'CommentID', '', $item, '=');
			$Result = $this->Context->Database->Select($s, $this->Name, 'SplitDiscussion', 'An error occurred while selecting comment properties.');
			// now we got the WhisperUserID value here
			while ($Row = $this->Context->Database->GetRow($Result)) {
				$WhisperUserID = $Row['WhisperUserID'];
				$AuthorUserID = $Row['AuthUserID'];
				$DateWhisper = $Row['DateCreated'];
				break; 
			}
			
			//ok now update the whipers tables if it's a whisper
			
			if ($WhisperUserID != 0 ) {
				$this->UpdateWhispersTables($WhisperUserID, $AuthorUserID, $currentDiscussionID, $NewDisc, $DateWhisper);
				// and now update the from and to whisper columns in new Discussion

				$s->Clear();
				$s->SetMainTable('Discussion', 'd');
				$s->AddFieldNameValue('WhisperToLastUserID', $WhisperUserID);
				$s->AddFieldNameValue('WhisperFromLastUserID', $AuthorUserID);
				$s->AddFieldNameValue('DateLastWhisper', $DateWhisper);
				$s->AddWhere('d', 'DiscussionID', '', $NewDiscID, '=');
				$this->Context->Database->Update($s, $this->Name, 'SplitDiscussion', 'An error occurred while updating discussion properties.');
			}

			//if it is the first comment or the last we get the AuthUserID
			
			if ( ($j == 0) || ($j == (sizeof($ComIDs) - 1)))
			{
				// now retrieve some info on the author of first comment and last comment
				$s->Clear();
				$s->SetMainTable('Comment', 'c');
				$s->AddSelect(array('AuthUserID','DateCreated','WhisperUserID'),'c');
				$s->AddWhere('c', 'CommentID', '', $item, '=');
				$Result = $this->Context->Database->Select($s, $this->Name, 'SplitDiscussion', 'An error occurred while updating discussion properties.');
				// ok now I get the whole thing....
				while ($Row = $this->Context->Database->GetRow($Result)) {
					$AuthorComment = $Row['AuthUserID'];
					$DateLastActive = $Row['DateCreated'];
					break; // I only need the first record
				}
				
			}
			
			// here we change the discussion id of the selected comments to the new splitted discussion 
			
			$s->Clear();
			$s->SetMainTable('Comment', 'c');
			$s->AddFieldNameValue('DiscussionID', $Discussion->Comment->DiscussionID);
			$s->AddWhere('c', 'CommentID', '', $item, '=');
			$this->Context->Database->Update($s, $this->Name, 'SplitDiscussion', 'An error occurred while updating discussion properties.');
			
			// We set the info retrieved to the new discussion
			// if first comment we set as firstcomment ID and it's author
			
			if ($j == 0 ) {
				$s->Clear();
				$s->SetMainTable('Discussion', 'd');
				$s->AddFieldNameValue('FirstCommentID', $item);
				$s->AddFieldNameValue('AuthUserID', $AuthorComment);
				$s->AddWhere('d', 'DiscussionID', '', $Discussion->Comment->DiscussionID, '=');
				$this->Context->Database->Update($s, $this->Name, 'SplitDiscussion', 'An error occurred while updating discussion properties.');
			} 
			
			//if last comment we set last userid and the date last active  	
			
			if ( $j == (sizeof($ComIDs) - 1) )
			{		
				$s->Clear();
				$s->SetMainTable('Discussion', 'd');
				$s->AddFieldNameValue('LastUserID', $AuthorComment);
				$s->AddFieldNameValue('DateLastActive',$DateLastActive);
				// had to do this little hack otherways the count of comment was
				// not correct because when it creates a new discussion he already
				// add 1 to the comment count and since we add 1 to each comment
				// we got one more in the count.
				$s->AddFieldNameValue('CountComments', $this->Context->DatabaseColumns['Discussion']['CountComments'].'-1', '0');
				$s->AddWhere('d', 'DiscussionID', '', $Discussion->Comment->DiscussionID, '=');
				$this->Context->Database->Update($s, $this->Name, 'SplitDiscussion', 'An error occurred while updating discussion properties.');
			}
			
			// update counter of new discussion if it's not a whisper
			
				if ($WhisperUserID == 0){			
					$s->Clear();
					$s->SetMainTable('Discussion', 'd');
					$s->AddFieldNameValue('CountComments', $this->Context->DatabaseColumns['Discussion']['CountComments'].'+1', '0');
					$s->AddWhere('d', 'DiscussionID', '', $NewDisc, '=');
					$this->Context->Database->Update($s, $this->Name, 'SplitDiscussion', "An error occurred while updating the discussion's comment summary.");
				} 
			
			// update counter of current discussion if it's not a whisper
			
			if ($WhisperUserID == 0){			
				$s->Clear();
				$s->SetMainTable('Discussion', 'd');
				$s->AddFieldNameValue('CountComments', $this->Context->DatabaseColumns['Discussion']['CountComments'].'-1', '0');
				$s->AddWhere('d', 'DiscussionID', '', $currentDiscussionID, '=');
				$this->Context->Database->Update($s, $this->Name, 'SplitDiscussion', "An error occurred while updating the discussion's comment summary.");
			}
			
			// this is to update the last user to current discussion
			
			if ( $j == (sizeof($ComIDs) - 1) )
			{
				$s->Clear();
				$s->SetMainTable('Comment', 'c');
				$s->AddSelect(array('CommentID','AuthUserID','DateCreated'),'c');
				$s->AddWhere('c', 'DiscussionID', '', $currentDiscussionID, '=');
				$s->AddOrderBy('CommentID','c','desc');
				$s->AddLimit(0, 1);
				$Result = $this->Context->Database->Select($s, $this->Name, 'SplitDiscussion', 'An error occurred while updating discussion properties.');
				while ($Row = $this->Context->Database->GetRow($Result)) {
					$LastUserID = $Row['AuthUserID'];
					$DateLastActive = $Row['DateCreated'];
					break; 
				}
				
				//and now we store it to the discussion table
				
				$s->Clear();
				$s->SetMainTable('Discussion', 'd');
				$s->AddFieldNameValue('LastUserID', $LastUserID);
				$s->AddFieldNameValue('DateLastActive', $DateLastActive);
				$s->AddWhere('d', 'DiscussionID', '', $currentDiscussionID, '=');
				$this->Context->Database->Update($s, $this->Name, 'StartNewDiscAsMod', "An error occurred while updating the discussion's comment summary.");
				
				// and now update the from, to and date last whisper columns in currentDisc
				
				$this->updateFromToWhisperInDiscussion($currentDiscussionID);
			}
			
		}
		
		//TODO then go for the merge.. with whispers....
		
		if ($Discussion->Comment->DiscussionID) {
			// Saved successfully, so send back to the discussion
			// $Suffix = CleanupString($this->Discussion->Name).'/';
			header('location:'.GetUrl($this->Context->Configuration, 'comments.php', '', 'DiscussionID', $Discussion->Comment->DiscussionID, '', '', ''));
			die();
		}
		return $this->Context->WarningCollector->Iif();
	}
	
	
	function MergeDiscussion($ComIDs,$currentDiscussionID,$NewDiscussionID) {
		
		$s = $this->Context->ObjectFactory->NewContextObject($this->Context, 'SqlBuilder');
		
		//we make sure that the new discussion id exist
			
		if ($NewDiscussionID > $currentDiscussionID){
			$s->Clear();
			$s->SetMainTable('Discussion', 'd');
			$s->AddSelect('DiscussionID','d');
			$s->AddWhere('d', 'DiscussionID', '', $NewDiscussionID, '=');
			$s->AddOrderBy('DiscussionID','d','desc');
			$s->AddLimit(0, 1);
			$Result = $this->Context->Database->Select($s, $this->Name, 'MergeDiscussion', 'An error occurred while updating discussion properties.');
			while ($Row = $this->Context->Database->GetRow($Result)) {
				$LastDiscussionID = $Row['DiscussionID'];
				break; 
			}
			
			// if New discussion id greater than the last discussion id then we stop and show the error
			
			if ($NewDiscussionID > $LastDiscussionID) {
				$DiscussionID = $currentDiscussionID;
				// return $this->Context->WarningCollector->Add($this->Context->GetDefinition('WrongDiscussionID'));
				header('location:'.GetUrl($this->Context->Configuration, 'extension.php', '', '', '', '', 'PostBackAction=ShowError&DiscussionID='.$DiscussionID.'&error=WrongDiscussionID', ''));
				die();
			}
		}
		
		// we make sure that array is sorted ok!!
		
		sort($ComIDs);
		// we check if it's a total merge
			$s->Clear();
			$s->SetMainTable('Discussion', 'd');
			$s->AddSelect('CountComments','d');
			$s->AddSelect('TotalWhisperCount','d');
			$s->AddWhere('d', 'DiscussionID', '', $currentDiscussionID, '=');
			$Result = $this->Context->Database->Select($s, $this->Name, 'MergeDiscussion', 'An error occurred while updating discussion properties.');
			while ($Row = $this->Context->Database->GetRow($Result)) {
				$cc = $Row['CountComments'];
				$twc = $Row['TotalWhisperCount'];
				break; 
			}
		if ( sizeof($ComIDs) == ($cc + $twc) )
		{
			$cc = 'yes';
		} else {
			$cc = 'no';
		}
		//here we check the comments and merge them
		
		for ($j = 0; $j < sizeof($ComIDs); $j++) {
			$item = $ComIDs[$j];
			
			// we get info on the whispers before
			
			$s->Clear();
			$s->SetMainTable('Comment', 'c');
			$s->AddSelect(array('AuthUserID','WhisperUserID','DateCreated'),'c');
			$s->AddWhere('c', 'CommentID', '', $item, '=');
			$Result = $this->Context->Database->Select($s, $this->Name, 'MergeDiscussion', 'An error occurred while selecting comment properties.');
			// now we got the WhisperUserID value here
			while ($Row = $this->Context->Database->GetRow($Result)) {
				$WhisperUserID = $Row['WhisperUserID'];
				$AuthorUserID = $Row['AuthUserID'];
				$DateWhisper = $Row['DateCreated'];
				break; 
			}
			
			//ok now update the whipers tables if it's a whisper
			
			if ($WhisperUserID != 0 ) {
				$this->UpdateWhispersTables($WhisperUserID, $AuthorUserID, $currentDiscussionID, $NewDiscussionID, $DateWhisper);
				
				$s->Clear();
				$s->SetMainTable('Discussion', 'd');
				$s->AddFieldNameValue('WhisperToLastUserID', $WhisperUserID);
				$s->AddFieldNameValue('WhisperFromLastUserID', $AuthorUserID);
				$s->AddFieldNameValue('DateLastWhisper', $DateWhisper);
				$s->AddWhere('d', 'DiscussionID', '', $NewDiscussionID, '=');
				$this->Context->Database->Update($s, $this->Name, 'MergeDiscussion', 'An error occurred while updating discussion properties.');
			}
			//if it is the first comment or the last we get the AuthUserID
			
			if ( ($j == 0) || ($j == (sizeof($ComIDs) - 1)))
			{
				// now retrieve some info on the author of first comment
				$s->Clear();
				$s->SetMainTable('Comment', 'c');
				$s->AddSelect(array('AuthUserID','DateCreated','WhisperUserID'),'c');
				$s->AddWhere('c', 'CommentID', '', $item, '=');
				$Result = $this->Context->Database->Select($s, $this->Name, 'MergeDiscussion', 'An error occurred while updating discussion properties.');
				while ($Row = $this->Context->Database->GetRow($Result)) {
					$AuthorComment = $Row['AuthUserID'];
					$DateLastActive = $Row['DateCreated'];
					break; 
				}
			}
			
			
			
			
			// here we change the discussion id of the selected comments to the new merged discussion 
			
			$s->Clear();
			$s->SetMainTable('Comment', 'c');
			$s->AddFieldNameValue('DiscussionID', $NewDiscussionID);
			// if ($NewDiscussionID > $currentDiscussionID){
			// 	$s->AddFieldNameValue('DateCreated', MysqlDateTime());
			// }
			$s->AddWhere('c', 'CommentID', '', $item, '=');
			$this->Context->Database->Update($s, $this->Name, 'MergeDiscussion', 'An error occurred while updating discussion properties.');
			
			//here we get the DateLastActive only on the last comment obviously 
			
			// if ( $j == (sizeof($ComIDs) - 1) )
			// {
			// 	$s->Clear();
			// 	$s->SetMainTable('Comment', 'c');
			// 	$s->AddSelect('DateCreated','c');
			// 	$s->AddWhere('c', 'CommentID', '', $item, '=');
			// 	$Result = $this->Context->Database->Select($s, $this->Name, 'MergeDiscussion', 'An error occurred while updating discussion properties.');
			// 	// ok now I get the whole thing....
			// 	while ($Row = $this->Context->Database->GetRow($Result)) {
			// 		$DateLastActive = $Row['DateCreated'];
			// 		break; // I only need the first record
			// 	}
			// }

			// update count comments on the new discussion if not a whisper
			if ($WhisperUserID == 0) {
				$s->Clear();
				$s->SetMainTable('Discussion', 'd');
				$s->AddFieldNameValue('CountComments', $this->Context->DatabaseColumns['Discussion']['CountComments'].'+1', '0');
				$s->AddWhere('d', 'DiscussionID', '', $NewDiscussionID, '=');
				$this->Context->Database->Update($s, $this->Name, 'MergeDiscussion', 'An error occurred while updating discussion properties.');	
			}
			
			// if last comment we update the last user and date last active fields of the new discussion
			// TODO probably I've to do that at the end because if the last comment is a whisper...
			// this will  not work...
			if ( $j == (sizeof($ComIDs) - 1) )
			{
				$s->Clear();
				$s->SetMainTable('Discussion', 'd');
				$s->AddFieldNameValue('LastUserID', $AuthorComment);
				$s->AddFieldNameValue('DateLastActive', $DateLastActive);
				$s->AddWhere('d', 'DiscussionID', '', $NewDiscussionID, '=');
				$this->Context->Database->Update($s, $this->Name, 'MergeDiscussion', 'An error occurred while updating discussion properties.');
			}
			
				// now retrieve CountComments on the first $j so we are sure to get the total before any edit
				
				if ($j == 0)
				{
					$s->Clear();
					$s->SetMainTable('Discussion', 'd');
					$s->AddSelect('CountComments','d');
					$s->AddWhere('d', 'DiscussionID', '', $currentDiscussionID, '=');
					$Result = $this->Context->Database->Select($s, $this->Name, 'MergeDiscussion', 'An error occurred while updating discussion properties.');
					// ok now I get the whole thing....
					while ($Row = $this->Context->Database->GetRow($Result)) {
						$CountComments = $Row['CountComments'];
						break; // I only need the first record
					}
				}
			
			// we update the count comment on the current discussion
			
			if ( ($j == (sizeof($ComIDs) - 1)) && (sizeof($ComIDs)) != $CountComments && $WhisperUserID == 0)
			{
				$NewCountComments = $CountComments - (sizeof($ComIDs));
				// update counter
				$s->Clear();
				$s->SetMainTable('Discussion', 'd');
				$s->AddFieldNameValue('CountComments',$NewCountComments , '0');
				$s->AddWhere('d', 'DiscussionID', '', $currentDiscussionID, '=');
				$this->Context->Database->Update($s, $this->Name, 'MergeDiscussion', "An error occurred while updating the discussion's comment summary.");
				
				// this is to update the last user to current discussion
				$s->Clear();
				$s->SetMainTable('Comment', 'c');
				$s->AddSelect(array('CommentID','AuthUserID','DateCreated'),'c');
				$s->AddWhere('c', 'DiscussionID', '', $currentDiscussionID, '=');
				$s->AddOrderBy('CommentID','c','desc');
				$s->AddLimit(0, 1);
				$Result = $this->Context->Database->Select($s, $this->Name, 'MergeDiscussion', 'An error occurred while updating discussion properties.');
				while ($Row = $this->Context->Database->GetRow($Result)) {
					$LastUserID = $Row['AuthUserID'];
					$DateLastActiveCurrentDisc = $Row['DateCreated'];
					break; 
				}
				//and now we store it to the discussion table
				$s->Clear();
				$s->SetMainTable('Discussion', 'd');
				$s->AddFieldNameValue('LastUserID', $LastUserID);
				$s->AddFieldNameValue('DateLastActive', $DateLastActiveCurrentDisc);
				$s->AddWhere('d', 'DiscussionID', '', $currentDiscussionID, '=');
				$this->Context->Database->Update($s, $this->Name, 'MergeDiscussion', "An error occurred while updating the discussion's comment summary.");
			}
		}
			//if cc is yes we now that we selected all comments of 
			//current discussion so we need to delete it
		if ($cc == 'yes') {
			$s->Clear();
			$s->SetMainTable('Discussion', 'd');
			$s->AddWhere('d', 'DiscussionID', '', $currentDiscussionID, '=');
			$this->Context->Database->Delete($s, $this->Name, 'MergeDiscussion', "An error occurred while updating the discussion's comment summary.");
		}
		if ($NewDiscussionID) {
			// Saved successfully, so send back to the discussion
			header('location:'.GetUrl($this->Context->Configuration, 'comments.php', '', 'DiscussionID', $NewDiscussionID, '', '', ''));
			die();
		}
		return $this->Context->WarningCollector->Iif();
	}
	
	
	// this will be for next release...
	
	// function MoveDiscussionToTrash ($DiscussionID,$CategoryTrash)
	// {
	// 	$s = $this->Context->ObjectFactory->NewContextObject($this->Context, 'SqlBuilder');
	// 	$s->SetMainTable('Discussion', 'd');
	// 	$s->AddFieldNameValue('CategoryID', $CategoryTrash);
	// 	$s->AddWhere('d', 'DiscussionID', '', $DiscussionID, '=');
	// 	$this->Context->Database->Update($s, $this->Name, 'MoveDiscussionToTrash', 'An error occurred while updating discussion properties.');
	// 	if ($DiscussionID) {
	// 		// Saved successfully, so send back to the discussion
	//         $Suffix = CleanupString($this->Discussion->Name).'/';
	// 		header('location:'.GetUrl($this->Context->Configuration, '?CategoryID='.$CategoryTrash, '', 'DiscussionID', $DiscussionID, '', '', $Suffix));
	// 		die();
	// 	}
	// 	return $this->Context->WarningCollector->Iif();
	// }
	
	function MoveDiscussionToCategory ($DiscussionID,$CatID)
	{
		$s = $this->Context->ObjectFactory->NewContextObject($this->Context, 'SqlBuilder');
		$s->SetMainTable('Discussion', 'd');
		$s->AddFieldNameValue('CategoryID', $CatID);
		$s->AddWhere('d', 'DiscussionID', '', $DiscussionID, '=');
		$this->Context->Database->Update($s, $this->Name, 'MoveDiscussionToCategory', 'An error occurred while updating discussion properties.');
		if ($DiscussionID) {
			// Saved successfully, so send back to the discussion
			header('location:'.GetUrl($this->Context->Configuration, 'extension.php', '', '', '', '', 'PostBackAction=ShowModTools&DiscussionID='.$DiscussionID, ''));
			die();
		}
		return $this->Context->WarningCollector->Iif();
	}
	
	function EditSubjectOfDiscussion ($DiscussionID,$Subject)
	{
		// Validate the Discussion topic
		$Name = FormatStringForDatabaseInput($Subject);
		Validate('subjectTitle', 1, $Name, 100, '', $this->Context);
		$s = $this->Context->ObjectFactory->NewContextObject($this->Context, 'SqlBuilder');
		$s->SetMainTable('Discussion', 'd');
		$s->AddFieldNameValue('Name', $Name);
		$s->AddWhere('d', 'DiscussionID', '', $DiscussionID, '=');
		$this->Context->Database->Update($s, $this->Name, 'MoveDiscussionToCategory', 'An error occurred while updating discussion properties.');
		if ($DiscussionID) {
			// Saved successfully, so send back to the discussion
			header('location:'.GetUrl($this->Context->Configuration, 'extension.php', '', '', '', '', 'PostBackAction=ShowModTools&DiscussionID='.$DiscussionID.'', ''));
			die();
		}
		return $this->Context->WarningCollector->Iif();
	}
	
}



class saveDiscussionForm extends PostBackControl {
	var $FirstCommentID;
	var $FatalError;
	var $EditDiscussionID;
	var $Discussion;
	var $DiscussionFormattedForDisplay;
	var $DiscussionID;
	var $Comment;
	var $CommentID;
	var $Form;
	var $Title;
	var $CommentFormAttributes;
	var $DiscussionFormAttributes;
	var $myname;
	var $ok;
	var $CategoryTrash;
	var $Sticky;
	var $Close;
	
	
	function saveDiscussionForm (&$Context)
	{
		$this->Name = 'saveDiscussionForm';
		$this->ValidActions = array('Split', 'Merge','ShowModTools', 'ShowModSplit', 'ShowModMerge','TrashIt','MoveIt','EditSubject','ShowStartDiscAsMod','StartDiscAsMod','ShowError');
		$this->Constructor($Context);
		$this->Control($Context);
		$this->DiscussionFormAttributes = '';
		$this->PostBackAction = ForceIncomingString('Action', '');
		$this->Title = "Mod Tools";
		$this->DiscussionID = ForceIncomingInt('DiscussionID', 0);
		//check if theres all input by user
		
		if ( ForceIncomingString('PostBackAction','') == 'StartDiscAsMod' && ($_POST['Name']) && ($_POST['Body']))
		{
			$TopicName = $_POST['Name'];
			$CatID = $_POST['CategoryID'];
			if (isset($_POST['Sticky'])){$Sticky = 1;} else {$Sticky = 0;}
			if (isset($_POST['Close'])){$Close = 1;} else {$Close = 0;}
			$Body = $_POST['Body'];
			$ModerationManager = $Context->ObjectFactory->NewContextObject($this->Context, 'ModerationManager');
			$ModerationManager->StartNewDiscAsMod($TopicName,$Body,$CatID,$Sticky,$Close);
		}
		else if ( ForceIncomingString("PostBackAction", "") == 'StartDiscAsMod'){
			if ($_POST['Name'])
			{$this->Context->WarningCollector->Add($this->Context->GetDefinition('ForgetBody'));}
			if ($_POST['Body'])
			{$this->Context->WarningCollector->Add($this->Context->GetDefinition('ForgetNameField'));}
			if ( (!$_POST['Name']) && (!$_POST['Body']) )
			{$this->Context->WarningCollector->Add($this->Context->GetDefinition('ForgetBothNameBody'));}
		}
				
		if ( ForceIncomingString("PostBackAction", "") == 'Split' && ($_POST['Name']) && ($_POST['ComID']))
		{
			$TopicName = $_POST['Name'];
			$CatID = $_POST['CategoryID'];
			$ComIDs = $_POST['ComID'];
			$currentDiscussionID = $_POST['currentDisc'];
			$ModerationManager = $Context->ObjectFactory->NewContextObject($this->Context, 'ModerationManager');
			$ModerationManager->SplitDiscussion($TopicName,$CatID,$ComIDs,$currentDiscussionID);
		} 	// we give the different errors for the cases
			else if ( ForceIncomingString("PostBackAction", "") == 'Split'){
				$DiscussionID = $_POST['currentDisc'];
			if ($_POST['Name'])
			{
				header('location:'.GetUrl($this->Context->Configuration, 'extension.php', '', '', '', '', 'PostBackAction=ShowError&DiscussionID='.$DiscussionID.'&error=ForgetCheckComment', ''));
				die();
			}
			if ($_POST['ComID'])
			{
				header('location:'.GetUrl($this->Context->Configuration, 'extension.php', '', '', '', '', 'PostBackAction=ShowError&DiscussionID='.$DiscussionID.'&error=ForgetNameField', ''));
				die();
			}
			if ( (!$_POST['Name']) && (!$_POST['ComID']) )
			{
				header('location:'.GetUrl($this->Context->Configuration, 'extension.php', '', '', '', '', 'PostBackAction=ShowError&DiscussionID='.$DiscussionID.'&error=ForgetBoth', ''));
				die();
			}	
		}
		
		//check if theres all input by user
		if ( ForceIncomingString("PostBackAction", "") == 'Merge' && ($_POST['newDisc']) && ($_POST['ComID']) && ($_POST['currentDisc'] != $_POST['newDisc'] ) )
		{
			// $TopicName = $_POST['Name'];
			// $CatID = $_POST['CategoryID'];
			$ComIDs = $_POST['ComID'];
			$currentDiscussionID = $_POST['currentDisc'];
			$NewDiscussionID = $_POST['newDisc'];
				$ModerationManager = $Context->ObjectFactory->NewContextObject($this->Context, 'ModerationManager');
			$ModerationManager->MergeDiscussion($ComIDs,$currentDiscussionID,$NewDiscussionID);
		}	// we give the different errors for the cases
			else if ( ForceIncomingString("PostBackAction", "") == 'Merge'){
				$ComIDs = ForceIncomingInt('ComID',0);
				$NewDiscussionID = ForceIncomingInt('newDisc',0);
				$DiscussionID = ForceIncomingInt('currentDisc',0);
				if ($NewDiscussionID != 0)
					{
						header('location:'.GetUrl($this->Context->Configuration, 'extension.php', '', '', '', '', 'PostBackAction=ShowError&DiscussionID='.$DiscussionID.'&error=ForgetCheckComment', ''));
						die();
					}
				if ($ComIDs != 0)
					{
						header('location:'.GetUrl($this->Context->Configuration, 'extension.php', '', '', '', '', 'PostBackAction=ShowError&DiscussionID='.$DiscussionID.'&error=ForgetNewDiscField', ''));
						die();
					}
				if ( ($ComIDs == 0) && ($NewDiscussionID == 0 ))
				{
					header('location:'.GetUrl($this->Context->Configuration, 'extension.php', '', '', '', '', 'PostBackAction=ShowError&DiscussionID='.$DiscussionID.'&error=ForgetBoth', ''));
					die();
				}	
			}
			
			if ( ForceIncomingString('PostBackAction','') == 'MoveIt' )
			{
				$DiscussionID = $_GET['DiscussionID'];
				$CatID = $_GET['CategoryID'];
				$ModerationManager = $Context->ObjectFactory->NewContextObject($this->Context, 'ModerationManager');
				$ModerationManager->MoveDiscussionToCategory($DiscussionID,$CatID);
			}
		
			if ( ForceIncomingString('PostBackAction','') == 'EditSubject'  && ($_GET['Subject']))
			{
				$DiscussionID = $_GET['DiscussionID'];
				$Subject = $_GET['Subject'];
				$ModerationManager = $Context->ObjectFactory->NewContextObject($this->Context, 'ModerationManager');
				$ModerationManager->EditSubjectOfDiscussion($DiscussionID,$Subject);
			}
			
	}
	

	
	function Render ()
	{
		$this->CallDelegate('PreRender');
		if ( ForceIncomingString("PostBackAction", "") == 'ShowModSplit' )
		{
			include(dirname(__FILE__) . '/split_form.php');
		}
		if ( ForceIncomingString("PostBackAction", "") == 'ShowModMerge' )
		{
			include(dirname(__FILE__) . '/merge_form.php');
		}
		if ( ForceIncomingString("PostBackAction", "") == 'ShowStartDiscAsMod' )
		{
			include(dirname(__FILE__) . '/start_form.php');
		}
		if ( ForceIncomingString("PostBackAction", "") == 'ShowError' )
		{
			include(dirname(__FILE__) . '/show_error.php');
		}
		
		$this->CallDelegate('PostRender');
	}
}

if ( ($Context->Session->User->Permission('PERMISSION_MODERATE_COMMENTS'))  && (ForceIncomingString('PostBackAction','') == 'ShowModMerge' || ForceIncomingString('PostBackAction','') == 'ShowModSplit' || ForceIncomingString('PostBackAction','') == 'Split'   || ForceIncomingString('PostBackAction','') == 'Merge' || ForceIncomingString('PostBackAction','') == 'TrashIt' || ForceIncomingString('PostBackAction','') == 'MoveIt' || ForceIncomingString('PostBackAction','') == 'EditSubject' || ForceIncomingString('PostBackAction','') == 'ShowModTools' || ForceIncomingString('PostBackAction','') == 'ShowStartDiscAsMod' || ForceIncomingString('PostBackAction','') == 'StartDiscAsMod' || ForceIncomingString('PostBackAction','') == 'ShowError') )
{
	//Adds check box to comments
	$Context->AddToDelegate('CommentGrid', 'PostCommentOptionsRender', 'CommentOptions_AddSplit');
	function CommentOptions_AddSplit (&$Form)
	{

		$D = $GLOBALS['CommentGrid']->Discussion;
		$C = $Form->DelegateParameters['Comment'];
		if ( $Form->Context->Session->User->Permission('PERMISSION_MODERATE_COMMENTS') )
		{	
			$comIDCheckBox = GetDynamicCheckBox('ComID', 0, false,'SwitchCheckboxModTools('.$C->CommentID.');','SELECT','class="ComID"', $C->CommentID);
			
			// if split mode we omit to edit the first comment
			
			if (ForceIncomingString('PostBackAction','') == 'ShowModSplit'){
				if ($D->FirstCommentID != $C->CommentID){
					$Form->DelegateParameters['CommentList'] .= '&nbsp;'.$comIDCheckBox.'&nbsp;';
				}
			} else {$Form->DelegateParameters['CommentList'] .= '&nbsp;'.$comIDCheckBox.'&nbsp;';}
		}
	}
	
	$TabName = '';
	
	if(ForceIncomingString('PostBackAction','') == 'ShowModMerge'){
	$TabName = $Context->GetDefinition('MergeModeTab');
	} 
	if(ForceIncomingString('PostBackAction','') == 'ShowModSplit') {
		$TabName = $Context->GetDefinition('SplitModeTab');
		}
	if(ForceIncomingString('PostBackAction','') == 'ShowModTools') {
		$TabName = $Context->GetDefinition('ModModeTab');
		}
	if(ForceIncomingString('PostBackAction','') == 'ShowStartDiscAsMod') {
		$TabName = $Context->GetDefinition('StartModDisc');
		}
	
	if(ForceIncomingString('PostBackAction','') == 'ShowError'){
		$TabName = $Context->GetDefinition('ErrorModeTab');
	}
	
	$Menu->AddTab($TabName, 'modtools', GetUrl($Configuration, 'extension.php', '', '', '', '', 'PostBackAction=ModTools'), '', $Configuration['TAB_POSITION_MOD_TOOLS']);

		// 1. DEFINE VARIABLES AND PROPERTIES SPECIFIC TO THIS PAGE

		// Ensure the user is allowed to view this page
		$Context->Session->Check($Context);

		// Instantiate data managers to be used in this page
		$DiscussionManager = $Context->ObjectFactory->NewContextObject($Context, "DiscussionManager");
		$saveDiscussionForm = $Context->ObjectFactory->NewContextObject($Context,"saveDiscussionForm");		
		$catm = $Context->ObjectFactory->NewContextObject($Context, 'CategoryManager');

		// Create the comment grid
		$DiscussionID = ForceIncomingInt("DiscussionID", 0);
		if(ForceIncomingString('PostBackAction','') != 'ShowStartDiscAsMod'){	
			$CommentGrid = $Context->ObjectFactory->CreateControl($Context, "CommentGrid", $DiscussionManager, $DiscussionID);
		}
		// Define properties of the page controls that are specific to this page
		$Head->BodyId = 'CommentsPage';
		$Menu->CurrentTab = "modtools";
		$Panel->CssClass = "CommentPanel";
		$Panel->BodyCssClass = "Comments";
		if ( ForceIncomingString("PostBackAction", "") != 'ShowStartDiscAsMod' ){
		$Context->PageTitle = $CommentGrid->Discussion->Name;
		}

		// 2. BUILD PAGE CONTROLS

			// Create the comment footer
			$CommentFoot = $Context->ObjectFactory->CreateControl($Context, "CommentFoot");
		// 3. ADD CONTROLS TO THE PAGE
		
		
		$Title = $Context->GetDefinition('ModTools Options');
		$Panel->AddList($Title, 110);
				if ( ForceIncomingString("PostBackAction", "") != 'ShowModTools' ){
					if ( ForceIncomingString("PostBackAction", "") == 'ShowModSplit' )
					{$switchmode = 'Split';} else {$switchmode = 'Merge';} 
							$Panel->AddListItem($Title, 'Hide '.$switchmode.' Mode', './extension.php?PostBackAction=ShowModTools&DiscussionID='.$_GET['DiscussionID'].'"','','');
			}
			if ( ForceIncomingString("PostBackAction", "") != 'ShowModMerge' )	{
			$Panel->AddListItem($Title, $Context->GetDefinition('SwitchToMergeMode'), './extension.php?PostBackAction=ShowModMerge&DiscussionID='.$_GET['DiscussionID'].'"','','');
				}
				if ( ForceIncomingString("PostBackAction", "") != 'ShowModSplit' ){
			$Panel->AddListItem($Title, $Context->GetDefinition('SwitchToSplitMode'), './extension.php?PostBackAction=ShowModSplit&DiscussionID='.$_GET['DiscussionID'].'"','','');
			}
			if ( ForceIncomingString("PostBackAction", "") == 'ShowModMerge' ){
			$Panel->AddListItem($Title, $Context->GetDefinition('CheckAllForTotalMerge'), '','','id="checkAll" onclick="checkAll()"');
		}

		$mActions = $Context->GetDefinition('MoveDiscussionTo');
		$Panel->AddList($mActions, 110);
		
		// the category builder
		
		$CategoryData = $catm->GetCategories(0, 1);
		$cats = $Context->ObjectFactory->NewObject($Context, 'Select');
		$cats->Name = 'CategoryIDpanel';
		$cats->CssClass = 'CategorySelect';
		$cats->Attributes = ' id="ddCategoriesPanel" onChange="selectCategory(this.form.CategoryIDpanel.options[this.form.CategoryIDpanel.selectedIndex].value, \''.$_GET['DiscussionID'].'\' );"';
		$catego = $Context->ObjectFactory->NewObject($Context, 'Category');
		$LastBlocked = -1;
		while ($Row = $Context->Database->GetRow($CategoryData)) {
			$catego->Clear();
			$catego->GetPropertiesFromDataSet($Row);
			if ($catego->Blocked != $LastBlocked && $LastBlocked != -1) {
				$cats->AddOption("-1", "---", " disabled=\"true\"");
			}
			$cats->AddOption($catego->CategoryID, $catego->Name);
			$LastBlocked = $catego->Blocked;
		}
		
		$categorySelectPanel =
		      '<form><li>
		         '.$cats->Get()
		      .'</li></form>';
		
		$Panel->AddString($categorySelectPanel, 110, 110);
		$Panel->AddListItem($mActions, $Context->GetDefinition('MoveNow'), './extension.php?PostBackAction=MoveIt&DiscussionID='.$_GET['DiscussionID'].'&CategoryID=10"','','id="moveDiscussion"',118,118);

			// $Page->AddRenderControl($Head, $Configuration["CONTROL_POSITION_HEAD"]);
			// $Page->AddRenderControl($Menu, $Configuration["CONTROL_POSITION_MENU"]);
			// $Page->AddRenderControl($Panel, $Configuration["CONTROL_POSITION_PANEL"]);
			$Page->AddRenderControl($saveDiscussionForm, $Configuration["CONTROL_POSITION_PANEL"] + 9);
			// $Page->AddRenderControl($NoticeCollector, $Configuration['CONTROL_POSITION_NOTICES']);
			if ( ForceIncomingString("PostBackAction", "") != 'ShowStartDiscAsMod' ){
			$Page->AddRenderControl($CommentGrid, $Configuration["CONTROL_POSITION_BODY_ITEM"]);
		}
			// $Page->AddRenderControl($Foot, $Configuration["CONTROL_POSITION_FOOT"]);
			// $Page->AddRenderControl($PageEnd, $Configuration["CONTROL_POSITION_PAGE_END"]);

		// 4. FIRE PAGE EVENTS
			// $Page->FireEvents();
		

}

?>